package cn.kgc.appinfo.controller;

import cn.kgc.appinfo.advice.SysLogAdvice;
import cn.kgc.appinfo.common.condition.AppInfoCondition;
import cn.kgc.appinfo.common.utils.DTO;
import cn.kgc.appinfo.common.utils.Pager;
import cn.kgc.appinfo.entity.*;
import cn.kgc.appinfo.service.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/app_info")
public class AppInfoController {

    @Autowired
    private AppInfoService appInfoService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private AppCategoryService appCategoryService;

    @Autowired
    private AppVersionService appVersionService;

//    @Autowired
//    private SysLogService sysLogService;


    private Logger log = Logger.getLogger(AppInfoController.class);

    /**
     * 根据条件分页查询该用户开发的全部APP
     * @param condition
     * @param pager
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/show_app")
    public String showAppByCondition(AppInfoCondition condition, Pager pager, Model model, HttpSession session){

        DevUser devUser = (DevUser) session.getAttribute("user");

//        SysLog sysLog = new SysLog();
//        sysLog.setUsername(devUser.getDevCode());
//        sysLog.setUrl("/app_info/show_app");
//        sysLog.setMethodName("showAppByCondition");
//        sysLog.setOperateTime(new Date());
//        sysLog.setUserRoleName("开发者");
//        sysLog.setVisitTime(10);
//        sysLogService.saveSysLog(sysLog);


        condition.setDevUserId(devUser.getId());
        List<DataDictionary> appStatuses = dataDictionaryService.selectDataDictionaryByTypeCode("APP_STATUS");
        List<DataDictionary> appPlatforms = dataDictionaryService.selectDataDictionaryByTypeCode("APP_FLATFORM");
        List<AppCategory> appCategories = appCategoryService.selectAppCategoryByParentId(null);

        List<AppInfo> appInfos = appInfoService.selectAppInfoAllByAppInfoCondition(condition,pager);
        model.addAttribute("pager",pager);
        model.addAttribute("appInfos",appInfos);
        model.addAttribute("appStatuses",appStatuses);
        model.addAttribute("appPlatforms",appPlatforms);
        model.addAttribute("appCategoryies",appCategories);
        return "app_info/show_app";
    }

    @RequestMapping("/query_app_id/{id}")
    public String queryAppInfoById(@PathVariable Integer id,Model model){
        AppInfo appInfo = appInfoService.selectAppInfoById(id);
        List<AppVersion> appVersions = appVersionService.selectAppVersionByAppId(id);

        model.addAttribute("appInfo",appInfo);
        model.addAttribute("appVersions",appVersions);
        log.info("根据id查询"+appInfo);
        return "app_info/show_app_desc";
    }

    @RequestMapping("/alert_app_id/{id}")
    public String alertAppInfoById(@PathVariable Integer id,Model model){
        AppInfo appInfo = appInfoService.selectAppInfoById(id);
        model.addAttribute("appInfo",appInfo);

        List<DataDictionary> appPlatforms = dataDictionaryService.selectDataDictionaryByTypeCode("APP_FLATFORM");
        List<AppCategory> appCategories1 = appCategoryService.selectAppCategoryByParentId(null);
        List<AppCategory> appCategories2 = appCategoryService.selectAppCategoryByParentId(appInfo.getCategoryId1());
        List<AppCategory> appCategories3 = appCategoryService.selectAppCategoryByParentId(appInfo.getCategoryId2());
        model.addAttribute("appPlatforms",appPlatforms);
        model.addAttribute("appCategoryies1",appCategories1);
        model.addAttribute("appCategoryies2",appCategories2);
        model.addAttribute("appCategoryies3",appCategories3);
        return "app_info/alert_app_desc";
    }

    @RequestMapping("do_alert_app")
    public String alertAppInfo(AppInfo appInfo,MultipartFile upload,HttpServletRequest request) throws IOException {

        if(!upload.isEmpty()){
            String path = request.getServletContext().getRealPath("/uploads");

            File file = new File(path);
            if(!file.exists()){
                file.mkdir();
            }
            String originalFilename = upload.getOriginalFilename();

            appInfo.setLogoPicPath(request.getContextPath()+"/uploads/"+originalFilename);


            upload.transferTo(new File(path,originalFilename));
        }

        appInfoService.updataAppInfo(appInfo);
        return "redirect:/app_info/show_app";
    }

    @RequestMapping("/add_app")
    public String addApp(Model model){

        List<DataDictionary> appPlatforms = dataDictionaryService.selectDataDictionaryByTypeCode("APP_FLATFORM");
        List<AppCategory> appCategories = appCategoryService.selectAppCategoryByParentId(null);
        model.addAttribute("appPlatforms",appPlatforms);
        model.addAttribute("appCategoryies",appCategories);
        return "app_info/add_app";
    }

    @RequestMapping("/do_add_app")
    public String doAddApp(AppInfo appInfo, MultipartFile upload, HttpServletRequest request) throws IOException {
        log.info("添加新app");
//        System.out.println("添加");
        if(!upload.isEmpty()){
            String path = request.getServletContext().getRealPath("/uploads");

            File file = new File(path);
            if(!file.exists()){
                file.mkdir();
            }
            String originalFilename = upload.getOriginalFilename();

            appInfo.setLogoPicPath(request.getContextPath()+"/uploads/"+originalFilename);
            upload.transferTo(new File(path,originalFilename));
        }

        appInfo.setDevId(1);
        System.out.println("封装"+appInfo);
        log.info("封装信息"+appInfo.toString());

        appInfoService.addAppInfo(appInfo);


        return "redirect:/app_info/show_app";

    }

    @RequestMapping("/query_apk")
    public @ResponseBody DTO queryAppInfoCountByApkName(@RequestBody String apkName,DTO dto){


        int n = appInfoService.selectAppInfoCountByAPKName(apkName);

        if(n == 0){
            dto.setMsgCode(200);
            dto.setMsgString("文件名正常");
        }else {
            dto.setMsgCode(400);
            dto.setMsgString("文件名已被占用");
        }
       return dto;
    }
}
